package com.webserver.core;

import com.webserver.controller.ArticleController;
import com.webserver.controller.ToolsController;
import com.webserver.controller.UserController;
import com.webserver.http.HttpContext;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理请求环节
 */
public class DispatcherServlet {
    public void service(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        String path = request.getRequestURI();
        System.out.println("请求路径:" + path);
        //判断该请求路径是否为请求一个业务
        HandlerMapping.MethodMapping mm = HandlerMapping.getMethodMapping(path);
//        if ("/myweb/reg".equals(path)) {//该请求为注册页面上form表单提交的请求
//            UserController controller = new UserController();
//            controller.reg(request, response);
//        }
        if (mm != null) {
            mm.getMethod().invoke(mm.getController(), request, response);
        } else {
            File file = new File("./webapps" + path);
            if (file.isFile()) {//用户请求的是一个文件
                response.setEntity(file);//设置正文
            } else {//要么不存在，要么不是一个文件
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File("./webapps/root/404.html");
                response.setEntity(file);
            }
        }

        response.putHeader("Server", "WebServer");
    }
}
